package com.yong.springcloud.lb.impl;

import com.yong.springcloud.lb.LoadBalancer;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class MyLB implements LoadBalancer {

    /**
     * 负载均衡-轮询-算法：rest接口第几次请求数 % 服务器集群总数 = 实际调用服务器位置下标 ，
     * 每次服务重启后rest接口会从1开始计数
     */


    // 原子整型
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    /**
     * 采用自旋锁 避免多线程中采用synchronized 或 lock 锁的机制，加锁和解锁带来的时间消耗
     * @return
     */
    private final int getAndIncrement() {
        int current;
        int next;
        do {
            current = this.atomicInteger.get();
            next = current >= 2147483647 ? 0 : current + 1;
        } while (!this.atomicInteger.compareAndSet(current, next));
        return next;
    }

    @Override
    public ServiceInstance instance(List<ServiceInstance> serviceInstanceList) {
        int index = getAndIncrement() % serviceInstanceList.size();
        return serviceInstanceList.get(index);
    }
}
